package frame;

import dao.UserDAO;
import pojo.UserDO;
import service.UserService;
import service.impl.UserServiceImpl;
import util.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TransferMoney extends JPanel implements ActionListener {
    private Atm frame;
    private UserService userService = new UserServiceImpl();
    private Icon btnOff = Util.getIcon("/images/buttonOff.jpg");
    private Icon btnSure = Util.getIcon("/images/buttonSure.jpg");
    private JButton imageBtn1 = new JButton(btnOff);
    private JButton imageBtn2 = new JButton(btnSure);
    private JTextField nameText = new JTextField();
    private JTextField moneyText = new JTextField();

    public TransferMoney(Atm frame) {
        this.frame = frame;
        this.setLayout(null);
        this.setOpaque(false);

        JLabel acc1 = new JLabel("请输入转账账户:");
        acc1.setFont(new Font("宋体", Font.PLAIN, 20));
        acc1.setBounds(200, 200, 300, 50);
        this.add(acc1);
        JLabel acc = new JLabel("请输入转账金额:");
        acc.setFont(new Font("宋体", Font.PLAIN, 20));
        acc.setBounds(200, 300, 300, 50);
        this.add(acc);

        nameText.setBounds(400, 200, 300, 50);
        nameText.setFont(new Font("宋体", Font.PLAIN, 20));
        this.add(nameText);
        moneyText.setBounds(400, 300, 300, 50);
        moneyText.setFont(new Font("宋体", Font.PLAIN, 20));
        this.add(moneyText);


        imageBtn1.setBounds(650, 430, 140, 50);
        this.add(imageBtn1);
        imageBtn1.addActionListener(this);
        imageBtn2.setBounds(300, 430, 140, 50);
        this.add(imageBtn2);
        imageBtn2.addActionListener(this);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        UserDO user = new UserDO();
        UserDO otherUser = new UserDO();
        user = Util.query(frame.getUser().getAccount(), frame.getUser().getPsw());
        if (e.getSource() == imageBtn1) {
            frame.switchPanel("menu");
        } else if (e.getSource() == imageBtn2) {
            if (!moneyText.getText().matches("^[0-9]+(.[0-9]{1,2})?$")) {
                JOptionPane.showMessageDialog(this, "错误代码");
                return;
            }
            Double m = Double.parseDouble(moneyText.getText());

            try {
                userService.transferMoney(frame.getUser().getId(), nameText.getText(), m);
                JOptionPane.showMessageDialog(this, "转账成功");
            } catch (Exception exception) {
                JOptionPane.showMessageDialog(this, exception.getMessage());
            }
        }
    }
}

